package wiki.tools.vidition.droid;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import wiki.tools.vidition.droid.util.HttpClient;
import wiki.tools.vidition.droid.util.ManagerURL;
import wiki.tools.vidition.droid.util.bean.CategoryBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ShowCategory extends Activity {
	private static final String searchHeader = "http://en.wikipedia.org/w/api.php?action=query&generator=categorymembers&format=xml&prop=info&gcmtitle=Category:";
	private ListView listView;
	private ProgressBar progressBar;
	private TextView tip_textview;
	private TextView keyword_textview;
	private String keyword;
	private String searchuri;
	private ArrayList<CategoryBean> categoy;
	private static final int GETDATA_SUCCESS = 0;
	private static final int GETDATA_FAILED = 1;

	private TranslateAnimation translateAnimation;
	private AlphaAnimation animation;
	private ImageView car;
	private RelativeLayout cartoon;
	private boolean isShow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchrss);
		keyword = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		getView();
		isShow = true;
		keyword_textview.setText(keyword);
		searchuri = searchHeader + keyword;
		categoy = new ArrayList<CategoryBean>();
		new Thread(fectdata).start();

		car = new ImageView(this);
		car.setImageResource(R.drawable.car);

		cartoon.addView(car);

		translateAnimation = new TranslateAnimation(150, 150, 0, 480);
		translateAnimation.setDuration(2000);
		translateAnimation.setAnimationListener(carAnimationListener);
		car.startAnimation(translateAnimation);

		animation = new AlphaAnimation(1.0f, 0.2f);
		animation.setRepeatCount(0);
		animation.setDuration(2500);
		animation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				cartoon.setVisibility(View.GONE);

			}

			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

		});

	}

	AnimationListener carAnimationListener = new AnimationListener() {

		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			if (null != car && car.getParent() != null) {
				cartoon.removeView(car);
				car = null;
			}
			handler.sendEmptyMessage(15);
		}

		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub

		}

	};

	private void getView() {
		cartoon = (RelativeLayout) findViewById(R.id.searchrss_re);
		listView = (ListView) findViewById(R.id.searchrss_listview);
		tip_textview = (TextView) findViewById(R.id.searchrss_tip);
		progressBar = (ProgressBar) findViewById(R.id.searchrss_progressbar);
		keyword_textview = (TextView) findViewById(R.id.searchrss_keyword);
		tip_textview.setVisibility(View.GONE);
	}

	Runnable fectdata = new Runnable() {
		public void run() {
			HttpClient client = new HttpClient();
			String xmlContent = client.getMethod(searchuri, false);
			if (!TextUtils.isEmpty(xmlContent)) {
				try {
					Document doc = new SAXReader().read(new InputSource(
							new StringReader(xmlContent)));
					List list = doc.selectNodes("/api/query/pages/page");
					for (int i = 0; i < list.size(); i++) {
						CategoryBean bean = new CategoryBean();
						Element element = (Element) list.get(i);
						bean.title = element.attribute(2).getValue();
						bean.time = element.attribute(3).getValue();
						categoy.add(bean);
					}
					handler.sendEmptyMessage(GETDATA_SUCCESS);
				} catch (DocumentException e) {
					e.printStackTrace();
				}
			} else {
				handler.sendEmptyMessage(GETDATA_FAILED);
			}

		}
	};

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			progressBar.setVisibility(View.GONE);
			switch (msg.what) {
			case GETDATA_FAILED:
				isShow = false;
				cartoon.startAnimation(animation);
//				tip_textview
//						.setText("Can not get news, please check your network.");
				new AlertDialog.Builder(ShowCategory.this).setMessage(
				"Can not get news, please check your network.")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						ShowCategory.this.finish();
					}
				}).show();
				break;

			case GETDATA_SUCCESS:
				isShow = false;
				cartoon.startAnimation(animation);
				ShowCategroyAdapter adapter = new ShowCategroyAdapter(
						ShowCategory.this, categoy);
				listView.setScrollingCacheEnabled(false);
				listView.setClickable(true);
				listView.setAdapter(adapter);
				listView.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent intent = new Intent(ShowCategory.this,
								ShowUrlActivity.class);
						intent.putExtra(Intent.EXTRA_TITLE, categoy
								.get(position).title);
						intent.putExtra(Intent.EXTRA_TEXT, ManagerURL.loadURL
								+ categoy.get(position).title);
						startActivity(intent);
					}
				});
				break;
			case 15:
				if (isShow) {
					car = new ImageView(ShowCategory.this);
					car.setImageResource(R.drawable.car);
					cartoon.addView(car);
					car.startAnimation(translateAnimation);
				}
				break;
			}
		}

	};
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		setResult(Intent.FILL_IN_CATEGORIES);
		super.onDestroy();
	}
}